<?php

namespace App\Http\Controllers\Api;

use App\Models\Category;
use App\Models\Product;
use App\Models\ProductSku;
use Illuminate\Http\Request;

class ProductsController extends ApiController
{
    /**
     *
     * @return mixed
     */
    public function index()
    {
        // $products = Product::where('on_sale', 1)->with('category.specs', 'skus')->orderBy('sort')->get();
        $products = Product::where('on_sale', 1)->orderBy('sort')->get();
        $product_recommend = array();
        $product_new = array();
        $product_hot = array();
        foreach ($products as $product) {
            unset($product->description);
            unset($product->carousel_image);
            $p = $product->toArray();
            // $p['colors'] = $product->color_info->toArray();
            if ($product->is_hot) {
                $product_hot[] = $p;
            }
            if ($product->is_recommend) {
                $product_recommend[] = $p;
            }
            if ($product->is_new) {
                $product_new[] = $p;
            }
        }
        $data['products'] = $products;
        $data['h_products'] = $product_hot;
        $data['r_products'] = $product_recommend;
        $data['n_products'] = $product_new;
        return $this->success($data);
    }

    //返回指定分类商品
    public function getProductsBycategory(Request $request)
    {
        if (!$request->category) {
            return $this->success('请输入分类', 'error');
        }
        $category = Category::find($request->category);
        if (empty($category)) {
            return $this->success('分类不存在', 'error');
        }
        $products = Product::where(['on_sale' => 1, 'category_id' => $request->category])->orderBy('sort')->get();
        $productArr = array();
        foreach ($products as $product) {
            unset($product->description);
            unset($product->carousel_image);
            $p = $product->toArray();
            // $p['colors'] = $product->color_info->toArray();
            $productArr[] = $p;
        }
        $data['products'] = $productArr;
        $data['category_name'] = $category->name;
        return $this->success($data);
    }

    // 商品详情
    public function detail(Product $product)
    {
        // 产品id没找到
        if (empty($product)) {
            return $this->success('商品不存在', 'error');
        } else {
            // 商品已经下架
            if ($product->on_sale == 0) {
                return $this->success('商品已下架', 'error');
            }
            // 没有设置sku数据
            if (count($product->skus) == 0) {
                return $this->success('商品未设置规格信息', 'error');
            }
            // 遍历产品轮播图，为想醉路径设置前缀
            $carousel_images = array();
            foreach ($product->carousel_image as $img) {
                $carousel_images[] = $product->getImageUrl($img);
            }
            // 删除产品相对路径轮播图
            unset($product->carousel_image);
            // 赋值带前缀的轮播图数据给产品
            $product->carousel_images = $carousel_images;
            //为前端显示sku组合设计的数据，规格组、规格值
            $skus = $product->skus;
            //定义一个数组接收规格数据
            $arr = [];
            //遍历sku
            foreach ($skus as $sku) {
                //遍历每个sku的规格
                foreach ($sku->spec_items as $k => $spec) {
                    //判断当前规格是不是在数组中已经有创建
                    if (!isset($arr[$k])) {
                        $arr[$k] = [$spec];
                    } else {
                        // 遍历当前sku的规格值
                        $exist = false;
                        foreach ($arr[$k] as $a) {
                            // 判断当前sku的规格值在不在数组里面，存在则break返回
                            if ($a['item'] == $spec['item']) {
                                $exist = true;
                                break;
                            }
                        }
                        //当前规格值不在数组里面则添加进去
                        if (!$exist) {
                            $arr[$k] = array_merge($arr[$k], [$spec]);
                        }
                    }
                }
            }
            // 把规格数据放到产品信息里面
            $product->spec_info = array_values($arr);
            $data['product'] = $product;
            // 返回产品信息
            return $this->success($data);
        }
    }
    public function isFavored(Product $product)
    {
        $favored = false;
        // 用户未登录时返回的是 null，已登录时返回的是对应的用户对象
        if($user = auth('api')->user()) {
            // 从当前用户已收藏的商品中搜索 id 为当前商品 id 的商品
            // boolval() 函数用于把值转为布尔值
            $favored = boolval($user->favoriteProducts()->find($product->id));
        }
        $data['favored'] = $favored;
        return $this->success($data);
    }
    //获取指定商品的sku信息
    public function getSku(Request $request)
    {
        $product_id = $request->product_id;
        $spec_child_ids = $request->spec_child_ids;
        $spec_arr = array_filter(explode(',', $spec_child_ids));
        $where = [];
        $query = ProductSku::where('product_id', $product_id);
        foreach ($spec_arr as $arr) {
            $where = "\"" . explode(':', $arr)[0] . "\":{\"id\":" . explode(':', $arr)[1];
            $query = $query->where('spec_items', 'like', '%' . $where . '%');
        }
        $sku = $query->first();
        if (empty($sku)) {
            return $this->success('没有对应库存', 'error');
        }
        $data['sku'] = $sku;
        return $this->success($data);
    }
    //获取指定id的sku
    public function getSkuByid(Request $request)
    {
        $sku = ProductSku::with('product')->find($request->skuid);
        if (!empty($sku)) {
            $data['sku'] = $sku;
            return $this->success($data);
        }
        return $this->success('没有对应商品', 'error');
    }

    // 添加收藏接口
    public function favor(Product $product, Request $request)
    {
        $user = $request->user();
        if ($user->favoriteProducts()->find($product->id)) {
            return $this->success('已经收藏过了', 'error');
        }
        $user->favoriteProducts()->attach($product);
        $data['favored'] = true;
        return $this->success($data);
    }
    // 取消收藏接口
    public function disfavor(Product $product, Request $request)
    {
        $user = $request->user();
        $user->favoriteProducts()->detach($product);
        $data['favored'] = false;
        return $this->success($data);
    }
    // 收藏列表
    public function favorites(Request $request)
    {
        $products = $request->user()->favoriteProducts()->get();
        $data['products'] = $products ;
        return $this->success($data);
    }
}
